import '../BleBean.dart';
import 'package:lib_bt/bean/BleBeanInterface.dart';
import 'package:lib_bt/listener/CheckBleSupportInterface.dart';
import './OtaUtil.dart';

///是否是ota设备检测
class OtaBleSupportImpl implements CheckBleSupportInterface {
  static List<List> supportList = [
    [0xd6, 0x05, 0x41, 0x54, 0x4f, 0x4c, 0x4a]
  ];

  ///从bootloader状态下的广播报中获取mac地址
  String getOtaDeviceMac(List bytes) {
    String mac = "";
    if (bytes.length >= 14) {
      int startIndex = 13;
      mac += bytes[startIndex].toRadixString(16).padLeft(2, '0');
      mac += bytes[startIndex - 1].toRadixString(16).padLeft(2, '0');
      mac += bytes[startIndex - 2].toRadixString(16).padLeft(2, '0');
      mac += bytes[startIndex - 3].toRadixString(16).padLeft(2, '0');
      mac += bytes[startIndex - 4].toRadixString(16).padLeft(2, '0');
      mac += bytes[startIndex - 5].toRadixString(16).padLeft(2, '0');

      mac = mac.toLowerCase();
    }
    return mac;
  }

  @override
  BleBean? isSupport(BleBeanInterface bean) {
    BleBean colorBleBean = BleBean(bean:bean);
    List matchData = [];
    for (var l in supportList) {
      matchData = CheckBleSupportInterface.getMatchData(bean.bytes, l);
      if (matchData.isNotEmpty) {
        break;
      }
    }

    if (matchData.isEmpty) {
      return null;
    } else {
      //这是一个单备份的设备,已经进入bootloader状态,检测本机是否存有该设备的信息
      //print("这是一个单备份的设 ${bean.name}");
      String mac = getOtaDeviceMac(matchData);
      //print("这是一个单备份的设 ${bean.name}  mac:${mac}");
      var otaInfo = OtaUtil.getOtaInfo(mac);

      if (otaInfo != null && otaInfo.isNotEmpty) {
        colorBleBean.bytes = otaInfo;
        colorBleBean.isAutoConnect = false;
        return colorBleBean;
      }
    }
  }

  @override
  getSendInterface(BleBeanInterface bean) {
    return null;
  }

  @override
  String getUUIDInfo() {
    return "";
  }

  @override
  String getSupportName() {
    return "color OTA";
  }
}
